package com.example.lets;

import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.os.IBinder;
import android.provider.MediaStore;
import android.provider.MediaStore.Images.Media;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.bmob.BTPFileResponse;
import com.bmob.BmobPro;
import com.bmob.BmobProFile;
import com.bmob.btp.callback.DownloadListener;
import com.bmob.btp.callback.LocalThumbnailListener;
import com.bmob.btp.callback.UploadListener;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import cn.bmob.v3.BmobUser;
import cn.bmob.v3.datatype.BmobDate;
import cn.bmob.v3.datatype.BmobFile;
import cn.bmob.v3.datatype.BmobGeoPoint;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

public class InitiateEventActivity extends AppCompatActivity  {

	private EditText date;
	private EditText time;

	private SelectPicPopupWindow selWindow;
	private Uri photoUri = null;
	private String fileName = null;
	private BmobGeoPoint curLoc;
	private String mode;
	private String actiId;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_initiate_event);

		final Intent in = getIntent();
		mode = in.getStringExtra("mode");
		String title = in.getStringExtra("title");
		String aname = null;
		String description = null;
		String datetime = null;
		String place = null;
		String detail = null;
		String type = null;
		String picFileName = null;
		String sponsorId = null;
		if (mode.equals("edit")) {
			aname = in.getStringExtra("name");
			picFileName = in.getStringExtra("picFileName");
			description = in.getStringExtra("description");
			datetime = in.getStringExtra("time");
			place = in.getStringExtra("place");
			detail = in.getStringExtra("detail");
			type = in.getStringExtra("type");
			sponsorId = in.getStringExtra("sponsorId");
			actiId = in.getStringExtra("id");
		}

		///
		/// toolbar
		///
		Toolbar toolbar = (Toolbar) this.findViewById(R.id.initiate_event_toolbar);
		toolbar.setTitle(title);
		setSupportActionBar(toolbar);
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);
		toolbar.setNavigationOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View view) {
				Intent backIntent = new Intent(InitiateEventActivity.this, HomeActivity.class);
				startActivity(backIntent);
				finish();
			}
		});

		///
		/// image button
		///
		final ImageButton imgbtn = (ImageButton) this.findViewById(R.id.initiate_event_image);
		final TextView imgtext = (TextView) this.findViewById(R.id.initiate_event_image_hint);
		imgbtn.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {

				selWindow = new SelectPicPopupWindow(InitiateEventActivity.this, new OnClickListener() {
					public void onClick(View v) {

						selWindow.dismiss();

						int id = v.getId();
						if (id == R.id.btn_take_photo) {
							SimpleDateFormat timeStampFormat = new SimpleDateFormat("yyyy_MM_dd_HH_mm_ss");
							String filename = "Lets_Head_" + timeStampFormat.format(new Date());
							ContentValues values = new ContentValues();
							values.put(Media.TITLE, filename);
							Intent intent1 = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
							photoUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
							intent1.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
							startActivityForResult(intent1, 1);
						} else if (id == R.id.btn_pick_photo) {
							Intent intent2 = new Intent();
							intent2.setType("image/*");
							intent2.setAction(Intent.ACTION_GET_CONTENT);
							startActivityForResult(intent2, 2);
						} else {
							Log.i("bmob", "undefined button");
							Toast.makeText(InitiateEventActivity.this, "未定义的按钮！", Toast.LENGTH_SHORT).show();
						}
					}
				});

				selWindow.showAtLocation(InitiateEventActivity.this.findViewById(R.id.initiate_event_details),
						Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0);
			}
		});

		if (picFileName != null) { // 这一坨是为了给在修改活动的时候设置现有图片
			final Context context = InitiateEventActivity.this;
			String cacheDownloadPath = BmobPro.getInstance(context).getCacheDownloadDir() + "/" + picFileName;
			String[] name = picFileName.split("\\.");
			String newFileName = name[0] + "_3_300_0_100." + name[1];
			String cacheThumbnailPath = BmobPro.getInstance(context).getCacheThumbnailDir() + "/" + newFileName;


			if ((new File(cacheDownloadPath)).exists()) { // 判断是否存在文件

				if ((new File(cacheThumbnailPath)).exists()) { // 判断是否存在缓存

					Bitmap bm = BitmapFactory.decodeFile(cacheThumbnailPath);
					imgbtn.setImageBitmap(bm);
					imgtext.setVisibility(View.INVISIBLE);

				} else {
					BmobProFile.getInstance(context).getLocalThumbnail(cacheDownloadPath, 3, new LocalThumbnailListener() {

						@Override
						public void onSuccess(String thumbnailPath) {
							Bitmap bm = BitmapFactory.decodeFile(thumbnailPath);
							imgbtn.setImageBitmap(bm);
							imgtext.setVisibility(View.INVISIBLE);
						}

						@Override
						public void onError(int statuscode, String errormsg) {
						}
					});
				}

			} else {
				BmobProFile.getInstance(context).download(picFileName, new DownloadListener() {

					@Override
					public void onSuccess(String fullPath) {
						BmobProFile.getInstance(context).getLocalThumbnail(fullPath, 3, new LocalThumbnailListener() {

							@Override
							public void onSuccess(String thumbnailPath) {
								Log.i("bmob", "下载并生成成功：" + thumbnailPath);
								Bitmap bm = BitmapFactory.decodeFile(thumbnailPath);
								//photo.setImageBitmap(bm);
								imgbtn.setImageBitmap(bm);
								imgtext.setVisibility(View.INVISIBLE);
							}

							@Override
							public void onError(int statuscode, String errormsg) {
							}
						});
					}

					@Override
					public void onProgress(String localPath, int percent) {
						Log.i("bmob", "download-->onProgress :" + percent);
					}

					@Override
					public void onError(int statuscode, String errormsg) {
						Log.i("bmob", "下载出错：" + statuscode + "--" + errormsg);
						Toast.makeText(context, "下载出错：" + statuscode + "--" + errormsg, Toast.LENGTH_SHORT).show();
					}
				});
			}
		}
			/*
			if ((new File(cachePath)).exists()) { // 缓存存在直接加载
				Bitmap bm = BitmapFactory.decodeFile(cachePath);
				imgbtn.setImageBitmap(bm);
				imgtext.setVisibility(View.INVISIBLE);
			} else { // 缓存不存在需要从远程下载
				BTPFileResponse response = BmobProFile.getInstance(context).download(picFileName, new DownloadListener() {
					@Override
					public void onSuccess(String fullPath) {
						Bitmap bm = BitmapFactory.decodeFile(fullPath);
						imgbtn.setImageBitmap(bm);
						imgtext.setVisibility(View.INVISIBLE);
					}

					@Override
					public void onProgress(String localPath, int percent) {
						Log.i("bmob", "download-->onProgress :" + percent);
					}

					@Override
					public void onError(int statuscode, String errormsg) {
						Log.i("bmob", "下载出错：" + statuscode + "--" + errormsg);
						Toast.makeText(context, "下载出错：" + statuscode + "--" + errormsg, Toast.LENGTH_SHORT).show();
					}
				});
			}*/

		///
		/// topic
		///
		EditText name = (EditText) this.findViewById(R.id.initiate_event_topic);
		if (aname != null) name.setText(aname);

		///
		/// type
		///
		final CheckBox sport = (CheckBox) this.findViewById(R.id.initiate_event_type_sport);
		final CheckBox food = (CheckBox) this.findViewById(R.id.initiate_event_type_food);
		final CheckBox tour = (CheckBox) this.findViewById(R.id.initiate_event_type_tour);
		final CheckBox study = (CheckBox) this.findViewById(R.id.initiate_event_type_study);
		final CheckBox game = (CheckBox) this.findViewById(R.id.initiate_event_type_game);
		final CheckBox movie = (CheckBox) this.findViewById(R.id.initiate_event_type_movie);

		sport.setOnClickListener(new android.widget.CheckBox.OnClickListener() {
			@Override
			public void onClick(View v) {
				food.setChecked(false);
				tour.setChecked(false);
				study.setChecked(false);
				game.setChecked(false);
				movie.setChecked(false);
			}
		});

		food.setOnClickListener(new android.widget.CheckBox.OnClickListener() {
			@Override
			public void onClick(View v) {
				sport.setChecked(false);
				tour.setChecked(false);
				study.setChecked(false);
				game.setChecked(false);
				movie.setChecked(false);
			}
		});

		tour.setOnClickListener(new android.widget.CheckBox.OnClickListener() {
			@Override
			public void onClick(View v) {
				food.setChecked(false);
				sport.setChecked(false);
				study.setChecked(false);
				game.setChecked(false);
				movie.setChecked(false);
			}
		});

		study.setOnClickListener(new android.widget.CheckBox.OnClickListener() {
			@Override
			public void onClick(View v) {
				food.setChecked(false);
				tour.setChecked(false);
				sport.setChecked(false);
				game.setChecked(false);
				movie.setChecked(false);
			}
		});

		game.setOnClickListener(new android.widget.CheckBox.OnClickListener() {
			@Override
			public void onClick(View v) {
				food.setChecked(false);
				tour.setChecked(false);
				study.setChecked(false);
				sport.setChecked(false);
				movie.setChecked(false);
			}
		});

		movie.setOnClickListener(new android.widget.CheckBox.OnClickListener() {
			@Override
			public void onClick(View v) {
				food.setChecked(false);
				tour.setChecked(false);
				study.setChecked(false);
				game.setChecked(false);
				sport.setChecked(false);
			}
		});

		if (type != null) { // 这一坨是为了在修改活动信息的时候给type赋初值
			if (type.equals("tour")) tour.setChecked(true);
			else if (type.equals("game")) game.setChecked(true);
			else if (type.equals("sport")) sport.setChecked(true);
			else if (type.equals("study")) study.setChecked(true);
			else if (type.equals("food")) food.setChecked(true);
			else movie.setChecked(true);
		}

		///
		/// date & time
		///
		date = (EditText) this.findViewById(R.id.initiate_event_date);
		time = (EditText) this.findViewById(R.id.initiate_event_time);
		date.setInputType(InputType.TYPE_NULL); // don't show input
		time.setInputType(InputType.TYPE_NULL); // don't show input
		if (datetime != null) {
			String[] dt = datetime.split(" ");
			date.setText(dt[0]);
			time.setText(dt[1]);
		}

		date.setOnTouchListener(new EditText.OnTouchListener() {
			Calendar c = Calendar.getInstance();

			@Override
			public boolean onTouch(View view, MotionEvent event) {
				if (event.getAction() != MotionEvent.ACTION_UP) return false;

				int year = c.get(Calendar.YEAR);
				int month = c.get(Calendar.MONTH);
				int day = c.get(Calendar.DAY_OF_MONTH);

				new DatePickerDialog(InitiateEventActivity.this,
						new DatePickerDialog.OnDateSetListener() {
							@Override
							public void onDateSet(DatePicker view, int year,
												  int monthOfYear, int dayOfMonth) {
								c.set(Calendar.YEAR, year);
								c.set(Calendar.MONTH, monthOfYear);
								c.set(Calendar.DAY_OF_MONTH, dayOfMonth);
								date.setText(new SimpleDateFormat("yyyy-MM-dd").format(c.getTime()));
							}
						}, year, month, day).show();
				return true;
			}
		});


		time.setOnTouchListener(new EditText.OnTouchListener() {
			Calendar c = Calendar.getInstance();

			@Override
			public boolean onTouch(View view, MotionEvent event) {
				if (event.getAction() != MotionEvent.ACTION_UP) return false;

				int hour = c.get(Calendar.HOUR_OF_DAY);
				int minute = c.get(Calendar.MINUTE);

				new TimePickerDialog(InitiateEventActivity.this,
						new TimePickerDialog.OnTimeSetListener() {
							@Override
							public void onTimeSet(TimePicker view, int hour, int minute) {
								c.set(Calendar.HOUR_OF_DAY, hour);
								c.set(Calendar.MINUTE, minute);
								time.setText(new SimpleDateFormat("HH:mm").format(c.getTime()));
							}
						}, hour, minute, true).show();
				return true;
			}
		});

		///
		/// address
		///
		EditText at = (EditText) this.findViewById(R.id.initiate_event_base_address);
		EditText dt  = (EditText) this.findViewById(R.id.initiate_event_detail_address);
		if (place != null) at.setText(place);
		if (detail != null) dt.setText(detail);

		ImageView map = (ImageView) this.findViewById(R.id.initiate_event_map);
		map.setOnClickListener(new Button.OnClickListener() {
			public void onClick(View v) {
				Intent intent = new Intent();
				intent.setClass(InitiateEventActivity.this, BaiduMapActivity.class);
				startActivityForResult(intent, 4);
			}
		});

		///
		/// details
		///
		EditText details = (EditText) this.findViewById(R.id.initiate_event_details);
		if (description != null)
			details.setText(description);

		///
		/// send
		///
		toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
			@Override
			public boolean onMenuItemClick(MenuItem item) {
				String kind;

				if (sport.isChecked()) kind = "sport";
				else if (food.isChecked()) kind = "food";
				else if (study.isChecked()) kind = "study";
				else if (tour.isChecked()) kind = "tour";
				else if (movie.isChecked()) kind = "movie";
				else if (game.isChecked()) kind = "game";
				else {
					Toast.makeText(InitiateEventActivity.this, "请选择一个活动类别！",
							Toast.LENGTH_SHORT).show();
					return false;
				}
				initiateActivity(kind);

				return true;
			}
		});

	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.initiate_event, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle action bar item clicks here. The action bar will
		// automatically handle clicks on the Home/Up button, so long
		// as you specify a parent activity in AndroidManifest.xml.
		int id = item.getItemId();
		if (id == R.id.action_settings) {
			return true;
		}
		return super.onOptionsItemSelected(item);
	}

	@SuppressWarnings("deprecation")
	private void initiateActivity(String kind) {

		final User curUser = BmobUser.getCurrentUser(this, User.class);

		String sponsorId = curUser.getObjectId();
		String sponsorName = curUser.getNickname();

		String address = ((EditText) this.findViewById(R.id.initiate_event_base_address)).getText().toString();
		String details = ((EditText) this.findViewById(R.id.initiate_event_details)).getText().toString();
		String topic   = ((EditText) this.findViewById(R.id.initiate_event_topic)).getText().toString();
		String date    = ((EditText) this.findViewById(R.id.initiate_event_date)).getText().toString();
		String time    = ((EditText) this.findViewById(R.id.initiate_event_time)).getText().toString();
		String detailPlace = ((EditText) this.findViewById(R.id.initiate_event_detail_address)).getText().toString();

		if (fileName == null || fileName.equals("")) {
			Toast.makeText(InitiateEventActivity.this, "请上传一张图片，让您的活动吸引更多人吧！", Toast.LENGTH_SHORT).show();
			return;
		}

		if (topic.equals("") || topic.length() > 12) {
			Toast.makeText(InitiateEventActivity.this, "请为活动起一个名字，不多于10个字符", Toast.LENGTH_SHORT).show();
			return;
		}

		if (date.equals("")) {
			Toast.makeText(InitiateEventActivity.this, "请选择活动开始的日期", Toast.LENGTH_SHORT).show();
			return;
		}

		if (time.equals("")) {
			Toast.makeText(InitiateEventActivity.this, "请选择活动开始的时间", Toast.LENGTH_SHORT).show();
			return;
		}

		if (details.equals("")) {
			Toast.makeText(InitiateEventActivity.this, "请描述一下您的活动", Toast.LENGTH_SHORT).show();
			return;
		}

		if (address.equals("")) {
			Toast.makeText(InitiateEventActivity.this, "请选择您的活动地点", Toast.LENGTH_SHORT).show();
			return;
		}

		Calendar cal = Calendar.getInstance();
		int year = Integer.parseInt(date.substring(0, 4));
		int month = Integer.parseInt(date.substring(5, 7));
		int day = Integer.parseInt(date.substring(8, 10));
		int hour = Integer.parseInt(time.substring(0, 2));
		int minute = Integer.parseInt(time.substring(3, 4));
		cal.set(year, month, day, hour, minute);
		Date setdate = cal.getTime();
		Date curDate = Calendar.getInstance().getTime();

		if (curDate.after(setdate)) {
			Toast.makeText(InitiateEventActivity.this, "时间已过期", Toast.LENGTH_SHORT).show();
			return;
		}

		BmobDate bmobDate = new BmobDate(setdate);

		final File file = new File(fileName);
		if (!file.exists()) {
			Toast.makeText(this, "图片不存在", Toast.LENGTH_SHORT).show();
			return;
		}

		final UserActivity ac = new UserActivity();
		ac.setDescription(details);
		ac.setPlace(address);
		ac.setType(kind);
		ac.setName(topic);
		ac.setSponsorId(sponsorId);
		ac.setSponsorName(sponsorName);
		ac.setStartTime(bmobDate);
		ac.setDetailPlace(detailPlace);
		ac.setGpsAdd(curLoc);

		BmobProFile.getInstance(this).upload(fileName, new UploadListener() {

			@Override
			public void onSuccess(String fileName, String url, BmobFile file) {
				Log.i("bmob", fileName + "    " + file.getUrl());
				ac.setPhoto(file);
				ac.setPicFilename(fileName);
				if (mode.equals("edit")) {
					ac.setObjectId(actiId);
					ac.update(InitiateEventActivity.this, new UpdateListener() {

						@Override
						public void onSuccess() {
							Toast.makeText(InitiateEventActivity.this, "编辑活动成功！", Toast.LENGTH_SHORT).show();
							Log.i("bmob", "编辑活动成功！");
						}

						@Override
						public void onFailure(int i, String s) {
							Toast.makeText(InitiateEventActivity.this, "编辑活动失败！", Toast.LENGTH_SHORT).show();
							Log.i("bmob", "编辑活动失败！");
						}
					});
					Intent intent = new Intent();
					intent.setClass(InitiateEventActivity.this, HomeActivity.class);
					startActivity(intent);
					InitiateEventActivity.this.finish();
				} else {
					ac.setPeopleNumber(1);
					ac.save(InitiateEventActivity.this, new SaveListener() {

						@Override
						public void onSuccess() {
							Involvement in = new Involvement();
							in.setActivityId(ac.getObjectId()); // need check

							in.setSponsorId(curUser.getObjectId());
							in.setUserId(curUser.getObjectId());
							in.setUser(curUser);
							in.save(InitiateEventActivity.this, new SaveListener() {

								@Override
								public void onSuccess() {
									int num = curUser.getSponsornum() == null ? 0 : curUser.getSponsornum();
									curUser.setSponsornum(num + 1);
									curUser.update(InitiateEventActivity.this, new UpdateListener() {
										@Override
										public void onSuccess() {
											Toast.makeText(InitiateEventActivity.this, "活动创建成功", Toast.LENGTH_SHORT).show();
											Log.i("bmob", "活动创建成功");
										}

										@Override
										public void onFailure(int i, String s) {

										}
									});
									// TODO Auto-generated method stub
								}

								@Override
								public void onFailure(int code, String arg0) {
									// TODO Auto-generated method stub
								}
							});
							Intent intent = new Intent();
							intent.setClass(InitiateEventActivity.this, HomeActivity.class);
							startActivity(intent);
							InitiateEventActivity.this.finish();
						}

						@Override
						public void onFailure(int code, String arg0) {
							Toast.makeText(InitiateEventActivity.this, "活动创建失败", Toast.LENGTH_SHORT).show();
						}
					});
				}
			}

			@Override
			public void onProgress(int progress) {
				Log.i("bmob", "onProgress :" + progress);
			}

			@Override
			public void onError(int statuscode, String errormsg) {
				Log.i("bmob", "BTPFILE失败" + errormsg);
			}
		});
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
			case 1:
				if (resultCode == RESULT_OK) {
					Uri uri = null;
					if (data != null && data.getData() != null)
						uri = data.getData();
					else if (photoUri != null)
						uri = photoUri;
					else {
						//Toast.makeText(this, "OnActivityResult出错，case1", Toast.LENGTH_SHORT).show();
					}
					cropPhoto(uri);
				}
				break;

			case 2:
				if (data != null) {
					Uri uri = data.getData();
					cropPhoto(uri);
					Log.e("uri", uri.toString());
				} else {
					Log.i("bmob", "ͼƬ�����ڣ�");
					//Toast.makeText(this, "OnActivityResult出错，case2", Toast.LENGTH_SHORT).show();
				}
				break;

			case 3:
				if (data != null) {
					Bundle extras = data.getExtras();
					Bitmap head = extras.getParcelable("data");
					if (head != null) {
						setPicToView(head);
						ImageView imageView = (ImageView) this.findViewById(R.id.initiate_event_image);
						imageView.setImageBitmap(head);
						TextView textView = (TextView) this.findViewById(R.id.initiate_event_image_hint);
						textView.setVisibility(View.INVISIBLE);
					}
				}
				break;

			case 4:
				Bundle bundle = data.getExtras();
				if (bundle != null) {
					EditText at = (EditText) this.findViewById(R.id.initiate_event_base_address);
					EditText dt  = (EditText) this.findViewById(R.id.initiate_event_detail_address);
					String base = bundle.getString("baseAddress");
					String detail = bundle.getString("detailAddress");
					if (base != null && !base.equals("")) at.setText(base);
					if (detail != null && detail.equals("")) dt.setText(detail);
					if (bundle.getString("latlng") != null) {
						String[] loc = bundle.getString("latlng").split(",");
						curLoc = new BmobGeoPoint(Double.parseDouble(loc[0]), Double.parseDouble(loc[1]));
					}
				}
			default:
				break;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	public void cropPhoto(Uri uri) {
		Intent intent = new Intent("com.android.camera.action.CROP");
		intent.setDataAndType(uri, "image/*");
		intent.putExtra("crop", "true");
		intent.putExtra("outputX", 200);
		intent.putExtra("outputY", 200);
		intent.putExtra("return-data", true);
		startActivityForResult(intent, 3);
	}

	private void setPicToView(Bitmap mBitmap) {
		String sdStatus = Environment.getExternalStorageState();
		if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) {
			return;
		}
		FileOutputStream b = null;
		String path = "/sdcard/Lets/myHead/";
		File file = new File(path);
		if (!file.exists())
			file.mkdirs();

		User curUser = BmobUser.getCurrentUser(this, User.class);
		fileName = path + curUser.getUsername() + "_head.jpg";
		try {
			b = new FileOutputStream(fileName);
			mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, b);
		} catch (FileNotFoundException e) {
			e.printStackTrace();
			Log.i("bmob", e.getMessage());
		} finally {
			try {
				b.flush();
				b.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	public void onBackPressed() {
		Intent backIntent = new Intent(InitiateEventActivity.this, HomeActivity.class);
		startActivity(backIntent);
		finish();
		return;
	}

	// get touch event
	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		// decide whether to shout off input
		if (ev.getAction() == MotionEvent.ACTION_DOWN) {
			View view = getCurrentFocus();
			if (isHideInput(view, ev)) {
				IBinder token = view.getWindowToken();
				if (token != null) {
					InputMethodManager manager =
							(InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
					manager.hideSoftInputFromWindow(token, InputMethodManager.HIDE_NOT_ALWAYS);
				}
			}
		}
		return super.dispatchTouchEvent(ev);
	}

	// judge whether need to shout off input
	private boolean isHideInput(View v, MotionEvent ev) {
		if (v != null && (v instanceof EditText)) {
			int[] l = { 0, 0 };
			v.getLocationInWindow(l);
			int left = l[0], top = l[1];
			int bottom = top + v.getHeight(), right = left + v.getWidth();
			if (ev.getX() > left && ev.getX() < right && ev.getY() > top
					&& ev.getY() < bottom) return false;
			else return true;
		}
		return false;
	}
}